<template>
  <el-dialog
    :title="`${data.id ? '修改' : '新增'}学科`"
    :visible.sync="dialogVisible"
    width="400px"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="科目名称" prop="subjectName">
        <el-input v-model="form.subjectName"></el-input>
      </el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay">
        <el-switch
          v-model="form.isFrontDisplay"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch
      ></el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add, update } from '../../api/hmmm/subjects'
export default {
  name: 'addsub',
  data () {
    return {
      dialogVisible: false,
      form: {
        id: null,
        subjectName: null,
        isFrontDisplay: '1'
      },
      rules: {
        subjectName: [
          {
            required: true,
            message: '科目名称不能为空',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  props: {
    data: {
      type: Object
    }
  },
  methods: {
    async confirm () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          if (!this.data.id) {
            // 新增
            await add(this.form)
          } else {
            // 编辑
            this.form.id = this.data.id
            await update(this.form)
          }
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.$emit('updateList')
        }
      })
    },
    open () {
      this.dialogVisible = true
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.form = { id, subjectName, isFrontDisplay }
      } else {
        this.form = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
